package com.shiro.handlers;

import com.shiro.services.ShiroServices;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/shiro")
public class ShiroHandler {

    @Autowired
    private ShiroServices shiroServices;

    @RequestMapping("/testShiroAnnotation")
    public String testShiroAnnotation(HttpSession  session) {
        session.setAttribute("key","val1234");
        shiroServices.testMethod();
        return "redirect:/list.jsp";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
        System.out.println("login===============================================");
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            token.setRememberMe(true);
            try {
                System.out.println("开始登录===============================================");
                subject.login(token);
            } catch (AuthenticationException e) {
                System.out.println("登录失败===============================================" + e.getMessage());

            }
        }
        return "redirect:/list.jsp";
    }
}
